<template>
  <div class="project_container flex">
    <TitleHeader title="项目" event-name="添加事件" @add="addEvent" />
    <div class="project_main flex-1">
      <ProjectNav />
      <ProjectMain />
    </div>
    <projectlist v-if="isShow != 0" />
  </div>
</template>

<script setup lang="ts">
import TitleHeader from '@/components/titleHeader/index.vue';
import ProjectNav from './project_nav.vue';
import ProjectMain from './project_main.vue';
import { ref, provide, defineAsyncComponent, onMounted, watchSyncEffect } from 'vue';
import { IProject, ITask } from '@/types/project';
import { getProjectList, getTaskByProjectId } from '@/api/projectApi';
import { concurrencyRequest } from '@/utils/request';

const projectlist = defineAsyncComponent(() => import('./projectlist.vue'));

const navItems = ref<IProject[]>([])
const navSelected = ref<IProject>()
const tasks = ref<{ current: ITask[], begin: ITask[] }>({
  current: [],
  begin: []
})
const map = new Map<IProject, { current: ITask[], begin: ITask[] }>()
const isShow = ref(0)
provide("navItems", navItems)
provide("navSelected", navSelected)
provide("isshow", isShow)
provide("tasks", tasks)

onMounted(() => {
  getProjectList().then(res => {
    navItems.value = res.data
    navSelected.value = res.data[0]
    getTaskList()
  })
})

watchSyncEffect(() => {
  if (!navSelected.value) return;
  if (map.get(navSelected.value)) {
    const res = map.get(navSelected.value)
    tasks.value.current = res!.current
    tasks.value.begin = res!.begin
    return;
  }
  getTaskList()
})
/**
 * 并发获取任务
 */
function getTaskList() {
  concurrencyRequest([
    () => getTaskByProjectId(navSelected.value!.id, 1),
    () => getTaskByProjectId(navSelected.value!.id, 2)]).then(res => {
      // @ts-ignore
      map.set(navSelected.value!, { current: res[0], begin: res[1] })
      // @ts-ignore
      tasks.value.current = res[0]
      // @ts-ignore
      tasks.value.begin = res[1]
    })
}

function addEvent() {
  console.log("添加项目");

}


</script>

<style lang="scss" scoped>
.project_container {
  overflow: hidden;
  position: relative;
  flex-direction: column;
  // height: 100%;
  flex: 1;
  padding-bottom: 10px;


  :deep(.header) {
    margin: 30px 0;
  }

  .project_main {
    // background-color: red;
    // height: 100%;
    display: flex;
    box-sizing: border-box;
    gap: 20px;
    flex: 1;
    // padding-bottom: 70px;
  }
}
</style>